<template>
  <div class="chat-container">
    <!-- 用户列表 -->
    <div class="user-list">
      <div class="user-list-header">
        <div class="current-user">
          <el-avatar :size="40" :src="currentUser.headPath">
            {{ currentUser.nickName ? currentUser.nickName.charAt(0) : 'U' }}
          </el-avatar>
          <div class="current-user-info">
            <div class="nickname">{{ currentUser.nickName || '未知用户' }}</div>
            <div class="status">在线</div>
          </div>
        </div>
      </div>
      <div class="user-list-content">
        <div v-if="userList.length === 0" class="no-users">
          <el-empty description="暂无用户"></el-empty>
        </div>
        <div v-else class="user-items">
          <div 
            v-for="user in userList" 
            :key="user.id"
            class="user-item"
            :class="{ 'active': searchForm.toId === user.id }"
            @click="selectUser(user)"
          >
            <el-avatar :size="40" :src="user.headPath">
              {{ user.nickName ? user.nickName.charAt(0) : 'U' }}
            </el-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.nickName }}</div>
              <div class="user-type">{{ user.toType === 'user' ? '普通用户' : '管理员' }}</div>
              <div v-if="unreadCounts[user.id]" class="unread-badge">
                {{ unreadCounts[user.id] }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-main">
      <!-- 聊天标题 -->
      <div class="chat-header">
        <span class="chat-title">{{ selectedUserName }}</span>
      </div>

      <!-- 聊天记录展示区 -->
      <div class="chat-history" ref="chatHistory">
        <div v-for="(message, index) in chatMessages" :key="index" 
             :class="['message-item', message.formType === 'admin' ? 'message-right' : 'message-left']">
          <div class="message-info">
            <div class="avatar">
              <el-avatar :size="40" :src="message.formType === 'admin' ? currentUser.headPath : selectedUserAvatar">
                {{ message.formType === 'admin' ? 
                  (currentUser.nickName ? currentUser.nickName.charAt(0) : 'U') : 
                  (selectedUserName ? selectedUserName.charAt(0) : 'U') }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="sender-name">{{ message.formType === 'admin' ? currentUser.nickName : selectedUserName }}</div>
              <div class="message-bubble">
                {{ message.content }}
              </div>
              <div class="message-time">{{ formatTime(message.time) }}</div>
            </div>
          </div>
        </div>

        <!-- 无数据提示 -->
        <div v-if="chatMessages.length === 0" class="no-data">
          <el-empty description="暂无聊天记录"></el-empty>
        </div>
      </div>

      <!-- 发送消息区域 -->
      <div class="message-input">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="4"
          placeholder="按 Ctrl + Enter 发送消息"
          @keyup.enter.native="handleEnter"
        >
        </el-input>
        <div class="message-actions">
          <el-button type="primary" @click="sendMessage" :disabled="!canSend">发送</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Chat',
  data() {
    return {
      searchForm: {
        toId: ''
      },
      chatMessages: [],
      newMessage: '',
      ws: null,
      token: JSON.parse(localStorage.getItem('loginUser')).token,
      userList: [],
      currentUser: {
        nickName: '',
        headPath: '',
        id: ''
      },
      selectedUserName: '',
      selectedUserAvatar: '',
      unreadCounts: {}
    }
  },
  computed: {
    canSend() {
      return this.searchForm.toId && this.newMessage.trim();
    }
  },
  methods: {
    // 获取当前用户信息
    fetchCurrentUserInfo() {
      this.$http.get('/zsd-permission/admin-info/selAdminInfo', {
        headers: {
          token: this.token
        }
      }).then(response => {
        if (response.data.code === null) {
          const adminInfo = response.data.data;
          this.currentUser = {
            nickName: adminInfo.name || adminInfo.username,
            headPath: 'https://smart116.oss-cn-chengdu.aliyuncs.com/%E5%A4%B4%E5%83%8F/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png',
            id: adminInfo.siteId,
            role: adminInfo.role
          };
        } else {
          this.$message.error('获取用户信息失败');
        }
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        this.$message.error('获取用户信息失败，请稍后重试');
      });
    },

    // 选择用户
    selectUser(user) {
      this.searchForm.toId = user.id;
      this.selectedUserName = user.nickName;
      this.selectedUserAvatar = user.headPath;
      this.unreadCounts[user.id] = 0;
      this.$forceUpdate();
      this.searchChatHistory();
    },

    // 初始化WebSocket连接
    initWebSocket() {
      const token = JSON.parse(localStorage.getItem('loginUser')).token;
      const wsUrl = `ws://192.168.40.61:8080/zsd-merchant/websocket?token=${token}`;
      this.ws = new WebSocket(wsUrl);

      this.ws.onopen = () => {
        console.log('WebSocket连接成功');
      };

      this.ws.onmessage = (e) => {
        console.log('收到消息:', e.data);
        const message = JSON.parse(e.data);
        
        // 如果消息的to为空或者与当前用户匹配，说明是广播消息或发给当前用户的消息
        if (!message.to || message.to === this.token) {
          console.log("进来了1");
          // 将两个值都转换为字符串进行比较
          if (String(this.searchForm.toId) === String(message.form)) {
            console.log("2");
            console.log("当前聊天对象ID:", this.searchForm.toId);
            console.log("消息发送者ID:", message.form);
            
            this.chatMessages.push(message);
            console.log(this.chatMessages);
            
            this.$nextTick(() => {
              this.scrollToBottom();
            });
          } else {
            // 如果不是当前聊天的用户，增加未读计数
            const senderId = message.form;
            if (senderId) {
              this.unreadCounts[senderId] = (this.unreadCounts[senderId] || 0) + 1;
              this.$forceUpdate();
            }
          }
        }
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.$message.error('连接错误，请刷新页面重试');
      };

      this.ws.onclose = () => {
        console.log('WebSocket连接关闭');
        setTimeout(() => {
          this.initWebSocket();
        }, 3000);
      };
    },

    // 查询聊天记录
    searchChatHistory() {
      this.$http.get('/zsd-merchant/chat-history/query', {
        params: {
          toId: this.searchForm.toId
        },
        headers: {
          token: localStorage.getItem('loginUser')
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.chatMessages = response.data.data;
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          this.$message.error(response.data.msg || '查询失败');
        }
      }).catch(error => {
        console.error('查询聊天记录失败:', error);
        this.$message.error('查询失败，请稍后重试');
      });
    },

    // 发送消息
    sendMessage() {
      if (!this.canSend) return;

      const message = {
        content: this.newMessage,
        to: this.searchForm.toId,
        type: 'text',
        form: this.token,
        formType: 'admin',
        time: new Date().toISOString()
      };

      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.ws.send(JSON.stringify(message));
        this.chatMessages.push({
          ...message,
          time: message.time.replace('T', ' ')
        });
        this.newMessage = '';
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      } else {
        this.$message.error('连接已断开，请刷新页面重试');
      }
    },

    // 处理回车键
    handleEnter(e) {
      if (e.ctrlKey && e.keyCode === 13) {
        this.sendMessage();
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      return time.replace('T', ' ');
    },

    // 滚动到底部
    scrollToBottom() {
      const chatHistory = this.$refs.chatHistory;
      if (chatHistory) {
        chatHistory.scrollTop = chatHistory.scrollHeight;
      }
    },

    // 获取用户列表
    fetchUserList() {
      this.$http.get('/zsd-merchant/chat-history/query/toInfo', {
        headers: {
          token: this.token
        }
      }).then(response => {
        if (response.data.code === 200) {
          this.userList = response.data.data;
          // 如果有选中的用户，更新选中用户的信息
          if (this.searchForm.toId) {
            const selectedUser = this.userList.find(user => user.id === this.searchForm.toId);
            if (selectedUser) {
              this.selectedUserName = selectedUser.nickName;
              this.selectedUserAvatar = selectedUser.headPath;
            }
          }
        } else {
          this.$message.error('获取用户列表失败');
        }
      }).catch(error => {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败，请稍后重试');
      });
    }
  },
  created() {
    this.fetchCurrentUserInfo();
    this.initWebSocket();
    this.fetchUserList();
  },
  beforeDestroy() {
    // 组件销毁前关闭WebSocket连接
    if (this.ws) {
      this.ws.close();
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: calc(100vh - 60px);
  padding: 0;
  background-color: #f5f7fa;
  display: flex;
  margin: 0;
}

.user-list {
  width: 250px;
  background-color: #2d3a4b;
  display: flex;
  flex-direction: column;
}

.user-list-header {
  padding: 15px;
  border-bottom: 1px solid #3a4b5e;
}

.current-user {
  display: flex;
  align-items: center;
  padding: 10px;
}

.current-user-info {
  margin-left: 10px;
  color: #fff;
}

.nickname {
  font-size: 16px;
  font-weight: 500;
}

.status {
  font-size: 12px;
  color: #67c23a;
  margin-top: 4px;
}

.user-list-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.user-items {
  display: flex;
  flex-direction: column;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 4px;
}

.user-item:hover {
  background-color: #3a4b5e;
}

.user-item.active {
  background-color: #3a4b5e;
}

.user-info {
  margin-left: 12px;
  color: #fff;
  position: relative;
}

.user-name {
  font-size: 14px;
  margin-bottom: 4px;
}

.user-type {
  font-size: 12px;
  color: #909399;
}

.unread-badge {
  position: absolute;
  top: -8px;
  right: -8px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 8px;
  font-size: 12px;
  padding: 0 4px;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-header {
  padding: 16px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.chat-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fff;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #fff;
}

.message-actions {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.message-item {
  margin-bottom: 20px;
}

.message-info {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
}

.message-left .message-info {
  margin-right: auto;
}

.message-right .message-info {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  margin: 0 12px;
}

.message-content {
  display: flex;
  flex-direction: column;
}

.message-right .message-content {
  align-items: flex-end;
}

.sender-name {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 4px;
  max-width: 100%;
  word-break: break-word;
  position: relative;
  font-size: 14px;
  line-height: 1.4;
}

.message-left .message-bubble {
  background-color: #fff;
  margin-right: 40px;
  border-radius: 0 8px 8px 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.message-right .message-bubble {
  background-color: #95ec69;
  margin-left: 40px;
  border-radius: 8px 0 8px 8px;
  color: #000;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.message-right .message-time {
  text-align: right;
}

.message-left .message-time {
  text-align: left;
}

.no-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
}

.user-list-content::-webkit-scrollbar-thumb {
  background: #3a4b5e;
}

.user-list-content::-webkit-scrollbar-track {
  background: #2d3a4b;
}
</style>